<?php

$this->useClass("Handler_Comments");
class Action_Community_UpdateComment extends Handler_Comments
{
	protected function init() {
		parent::init();
		$this->ctx->db->begin();
				
		$this->m_item = $this->ctx->mm->getModel("Item", "m");
		$this->m_user = $this->ctx->mm->getModel("User", "m");
		$this->m_tdi = $this->ctx->mm->getModel("Tdi", "m");		
	}
	
	protected function shutdown() {
		$this->ctx->db->end();
	}
		
	public function process()
	{
		$comment = $this->m_comment->getOneCommentAsObject( $this->params['id_comment'] );
		
		$this->aa->setItemOid( $comment->data['item_oid'] );
		$this->data = $this->aa->getInfo();
		$this->aa->getAvailableOperations();
		
		$this->aa->checkDeletions( array($this, "shutdown") );
		
		if ( isset($this->rh->POST['cancel']) ) {
			$feed_url = $this->rh->base_url.$this->data['community_url']."/showfeed";
			header("Location: ".$feed_url);
		} elseif ( isset($this->rh->POST["comment"]) ) {
			
			$status = $this->updateCommentSmart($comment->id, $this->rh->POST["comment"], $this->data['user_id']);

			switch($status) {
				case COMMENT_ACCESSDENIED:
				$message = "Нет доступа.";
				break;

				case COMMENT_EMPTYBODY:
				$message = "Нельзя сабмитить пустой коммент.";
				break;

				case COMMENT_UPDATED:
				break;

				case COMMENT_DELETED:
				$message = "Нельзя править удаленный комментарий.";
				break;
			}
			$view = $this->rh->views->findByName('update_success');
			$view->data = $this->aa->template_data;
			$view->data['message'] = $message;
			$view->data['item_oid'] = $comment->data['item_oid'];
			
			if (!$this->ctx->db->isErrorInTransaction()) {
				$this->rh->response->setContent($view);				
			} else {
				echo "Ошибка при завершении транзакции.";
			}
		} else {

			$item = $this->m_item->getItem( $comment->data['item_oid'] );
			$poster = $this->m_user->getUser( $item->data['posted_by_id'] );
			$tdi_instance = $this->m_tdi->getTdi( $item->data['tdi_oid'] );	
			
			$view = $this->rh->views->findByName('post');

			$view->data = $this->aa->template_data;

			$view->data['poster'] = $poster->data;
			$view->data['user']['oid']   = $this->data['user_id'];
			$view->data['user']['url']   = $this->data['user_id']; 
			$view->data['item'] = $item->data;
			$view->data['item_oid'] = $item->id;
			$view->data['tdi'] = $tdi_instance->data;
			
			$view->data['hide_comments_block'] = 1;
			$view->data['hide_form'] = 1;
			$view->data['update_form'] = 1;		

			// комментарий который правим
			$view->data['comment'] = $comment->data;
			$view->data['comment_oid'] = $this->params['id_comment'];
			$view->data['community_url'] = $this->aa->acl_data['community_url'];

			if (!$this->ctx->db->isErrorInTransaction()) {
				$this->rh->response->setContent($view);
			} else {
				echo "Ошибка при завершении транзакции.";
			}
		}
			
	} // end of function process

}
